package ex3;

import common.IRunnable;
import common.exceptions.ArgumentsException;
import common.exceptions.ParseException;
import common.exceptions.SemanticError;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 12/2/13
 */
public class Ex3 {

    public static void run(String[] args) {
        try {
            createRunnable(args).run();
        } catch(ParseException | ArgumentsException e) {
            System.out.println(e.getMessage());
        } catch(SemanticError e) {
            System.out.println(e);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Creates runnable according to program arguments
     * @param args program arguments
     * @return runnable
     * @throws Exception
     */
    private static IRunnable createRunnable(String args[]) throws Exception {
        if(args.length == 1) {
            return new SemanticAnalyzer.Builder()
                    .withProgramFilename(args[0])
                    .build();
        }
        else if(args.length == 2 && args[1].startsWith("-L")) {
            return new SemanticAnalyzer.Builder()
                    .withProgramFilename(args[0])
                    .withLibraryFilename(args[1].replaceAll("-L", ""))
                    .build();
        }
        else if(args.length >= 2) {
            Interpreter.Builder builder = new Interpreter.Builder();
            builder.withProgramFilename(args[0]);

            int index = 1;
            if(args[1].startsWith("-L")) {
                builder.withLibraryFilename(args[1].replaceAll("-L", ""));
                index++;
            }

            String[] classAndMethod = args[index].split("\\.");
            builder.withClass(classAndMethod[0]);
            builder.withMethod(classAndMethod[1], Arrays.copyOfRange(args, index + 1, args.length));

            return builder.build();
        }
        else {
            throw new ArgumentsException("Error: invalid arguments");
        }
    }
}
